package com.yunc.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.base.utils.BaseConstant;
import com.yunc.base.utils.R;
import com.yunc.modules.sys.entity.SysRole;
import com.yunc.modules.sys.entity.SysRoleDept;
import com.yunc.modules.sys.mapper.SysRoleDeptMapper;
import com.yunc.modules.sys.service.ISysRoleDeptService;
import com.yunc.modules.sys.service.ISysRoleService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统角色
 *
 * @author congcong tao
 * @date 2018/5/14 16:17
 */
@Service("sysRoleDeptService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysRoleDeptServiceImpl extends ServiceImpl<SysRoleDeptMapper, SysRoleDept> implements ISysRoleDeptService {

    private final SysRoleDeptMapper sysRoleDeptMapper;
    private final ISysRoleService sysRoleService;

    @Override
    public boolean insertList(String roleId, String deptIds) {
        if (StringUtils.isNotEmpty(deptIds)) {
            String[] roleIdArr = deptIds.split(",");
            if (roleIdArr != null && roleIdArr.length > 0) {
                List<SysRoleDept> sysRoleDeptList = new ArrayList<>();
                for (String deptId : roleIdArr) {
                    SysRoleDept roleDept = new SysRoleDept();
                    roleDept.setRoleId(roleId);
                    roleDept.setDeptId(deptId);
                    sysRoleDeptList.add(roleDept);
                }
                boolean flag = this.saveBatch(sysRoleDeptList);
                if (!flag) {
                    return false;
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public List<String> listDept(String userId) {
        return sysRoleDeptMapper.listDept(userId);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public R updateRole(String id, String dataScope, String deptIds) {
        SysRole sysRole = sysRoleService.getById(id);
        sysRole.setDataScope(dataScope);
        boolean flag = sysRoleService.updateById(sysRole);
        if (!flag) {
            return R.error();
        }
        QueryWrapper<SysRoleDept> qw = new QueryWrapper<>();
        qw.eq("role_id", id);
        this.remove(qw);
        // 重新保存
        if (StringUtils.equals(dataScope, BaseConstant.DATA_SCOPE_CUSTOM)) {
            insertList(id, deptIds);
        }
        return R.ok();
    }

    @Override
    public List<String> listDeptChild(String userId) {
        return sysRoleDeptMapper.listDeptChild(userId);
    }
}
